package com.fs.files.util;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;

public class FileUtil {
	
	public static File MultipartFileToFile(MultipartFile multipartFile) {
        File file = null;
        try {
             InputStream ins = null;
             ins = multipartFile.getInputStream();
             file = new File(multipartFile.getOriginalFilename());
             inputStreamToFile(ins, file);
             ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
    
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /****
	* @方法名称: WriteFile
	* @描述: 将数据写入到本地文件中
	* @param   @param str 数据内容
	* @param   @param filePath 写入文件的路径
	* @param   @param fileName 文件名称
	* @param   @return 
	* @return File 
	* @throws 
	* @author qiusx
	*/
	public static File WriteFile(String str,String filePath,String fileName){
		//写入文件
		File dir = new File(filePath);
		//目录不存在时创建目录
		if (!dir.exists()) {
			dir.mkdir();
		}
		filePath += fileName;
		try {
			FileWriter fileWriter = new FileWriter(filePath);
			fileWriter.write(str);
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new File(filePath);
	}


    /****
     * WriteEchartImag2File
     * @param echartImagData
     * @param filePath
     * @return
     */
	public static void WriteEchartImag2File(String echartImagData,String filePath){
        echartImagData = echartImagData.replaceAll(" ", "+");
		if (StringUtils.isEmpty(echartImagData)) {
			return ;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		String[] arr = echartImagData.split("base64,");
		// 数据中： ...  在"base64,"之后的才是图片信息
		try {
			byte[] buffer = decoder.decodeBuffer(arr[1]);
			OutputStream os = new FileOutputStream(new File(filePath));
			os.write(buffer);
			os.close();
		} catch (IOException e) {
			throw new RuntimeException();
		}
	}

}
